package com.lumlord.common.shiro.service;

 
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lumlord.common.domain.User;
import com.lumlord.common.shiro.util.JwtUtils;
import com.lumlord.util.RedisUtil;

import java.util.*;

import javax.annotation.Resource;

/**
 * 重写Shiro的Cache保存读取
 * @author gpf
 * @date 2019/10/11 14:31
 */
@Component
public class CustomCache<K,V> implements Cache<K,V> {



    /**
     * 缓存的key名称获取为shiro:cache:account
     * @param key
     * @return java.lang.String
     */
    private String getKey(Object key){
    	PrincipalCollection principal = (PrincipalCollection) key;
    	User user = (User) (principal.getPrimaryPrincipal());
    	if(null == user.getTooken()) {
    		String tooken = jwtUtils.sign(user.getAccount());
    		user.setTooken(tooken);
    	}
    	 
        return user.getTooken();// JwtUtils.getUsername(key.toString());
    }
     
    /**
     * 获取缓存
     */
    @Override
    public Object get(Object key) throws CacheException {
    	if(!redisUtil.hasKey(key.toString())){
            return null;
        }
        return redisUtil.get(key.toString());
    }

    /**
     * 保存缓存
     */
    @Override
    public Object put(Object key, Object value) throws CacheException {
        // 设置Redis的Shiro缓存
    	redisUtil.set(this.getKey(key).toString(), value.toString(), 3000);
       return value;
    }

    /**
     * 移除缓存
     */
    @Override
    public Object remove(Object key) throws CacheException {
    //    redisUtil.delete(getKey(key));
    	String tooken = getKey(key);
        return null;
    }

    /**
     * 清空所有缓存
     */
    @Override
    public void clear() throws CacheException {
    	System.out.println("清楚");
    }

    /**
     * 缓存的个数
     */
    @Override
    public int size() {
      
        return 0;
    }

    /**
     * 获取所有的key
     */
    @Override
    public Set keys() {
        /*Set<byte[]> keys = jwt.getJedis().keys(new String("*").getBytes());
        Set<Object> set = new HashSet<Object>();
        for (byte[] bs : keys) {
            set.add(SerializableUtil.unserializable(bs));
        }
        return set;*/
    	System.out.println("set");
    	return null;
    }

    /**
     * 获取所有的value
     */
    @Override
    public Collection values() {
        Set keys = this.keys();
        List<Object> values = new ArrayList<Object>();
        for (Object key : keys) {
            values.add(redisUtil.get(getKey(key)));
        }
        return values;
    }
	@Autowired
	private JwtUtils jwtUtils;
    @Autowired
    private RedisUtil redisUtil;
} 
